<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    // 定时器版本
    // 测试数据
    function test() {
      console.log("test被调用-->", this.data);
    }

    var data = 22;
    function throttle(fn, wait = 400) {
      var timer = null;
      return function () {
        var context = this;
        var args = arguments;
        if (!timer) {
          timer = setTimeout(function () {
            fn.apply(context, args);
            // 如果采用下面的写法则指向了window
            // fn(args);
            timer = null;
          }, wait);
        }
      };
    }

    // 模拟持续点击
    let n = 0;
    let obj = {
      data: 1,
      func: throttle(test),
    };

    const newFn = throttle(obj.func, 200);
    let timmer = setInterval(() => {
      n++;
      if (n == 20) {
        clearInterval(timmer);
      }
      console.log("持续点击");
      obj.func();
    }, 100);
  </script>
</html>
